﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Data;
using System.Text;
using System.Web;
using System.Transactions;
using FreedomERP.Services.Bd.Impl;
using FreedomERP.Models;
using FreedomERP.Comm;
using FreedomERP.Comm.Utils;
using FreedomERP.Comm.DB;

namespace FreedomERP.Dao.Bd.Impl
{
    public class BdCategoryDaoImpl : IBdCategoryDao
    {


        FreedomERPEntities dbEntities = new FreedomERPEntities();


        public DAOResult<BdCategory> findBdCategories(String fId, String fOrgunited, String fType, String fName, String fNumber, String fRemark, String fStatus, Boolean isDesc, int start, int limit, out int totalCount)
        {
            Expression<Func<BdCategory, bool>> predicate = PredicateExtensions.True<BdCategory>();
            if (fId != null && ConstData.EMPTY_STRING != fId)
            {
                predicate = predicate.And(cat => cat.FId.Contains(fId));
            }
            if (fOrgunited != null && ConstData.EMPTY_STRING != fOrgunited)
            {
                predicate = predicate.And(cat => cat.FOrgunitId.Contains(fOrgunited));
            }
            if (fType != null && ConstData.EMPTY_STRING != fType)
            {
                predicate = predicate.And(cat => cat.FType.Contains(fType));
            }
            if (fName != null && ConstData.EMPTY_STRING != fName)
            {
                predicate = predicate.And(cat => cat.FName.Contains(fName));
            }
            if (fNumber != null && ConstData.EMPTY_STRING != fNumber)
            {
                predicate = predicate.And(cat => cat.FNumber.Contains(fNumber));
            }
            if (fRemark != null && ConstData.EMPTY_STRING != fRemark)
            {
                predicate = predicate.And(cat => cat.FRemark.Contains(fRemark));
            }

            if (fStatus != null && ConstData.EMPTY_STRING != fStatus)
            {
                predicate = predicate.And(cat => cat.FStatus.Equals(fStatus));
            }

            List<BdCategory> prodCategories = null;
            var query = dbEntities.BdCategory.Where(predicate);
            totalCount = query.Count();
            if (isDesc)
            {
                prodCategories = query.OrderByDescending(cat => cat.FOrder).Skip(start).Take(limit).ToList();
            }
            else
            {
                prodCategories = query.OrderBy(cat => cat.FOrder).Skip(start).Take(limit).ToList();
            }
            return new DAOResult<BdCategory>(true, null, prodCategories);
        }

        public DAOResult<BdCategory> findProdModelTypes(String fId, String fOrgunited, String fName, String fNumber, String fRemark, String fStatus, Boolean isDesc, int start, int limit, out int totalCount)
        {

            Expression<Func<BdCategory, bool>> predicate = PredicateExtensions.True<BdCategory>();
            if (fId != null && ConstData.EMPTY_STRING != fId)
            {
                predicate = predicate.And(cat => cat.FId.Contains(fId));
            }
            if (fOrgunited != null && ConstData.EMPTY_STRING != fOrgunited)
            {
                predicate = predicate.And(cat => cat.FOrgunitId.Contains(fOrgunited));
            }

            predicate = predicate.And(cat => cat.FType.Equals(ConstData.CATEGORY_PROD_MODEL_TYPE));

            if (fName != null && ConstData.EMPTY_STRING != fName)
            {
                predicate = predicate.And(cat => cat.FName.Contains(fName));
            }
            if (fNumber != null && ConstData.EMPTY_STRING != fNumber)
            {
                predicate = predicate.And(cat => cat.FNumber.Contains(fNumber));
            }
            if (fRemark != null && ConstData.EMPTY_STRING != fRemark)
            {
                predicate = predicate.And(cat => cat.FRemark.Contains(fRemark));
            }

            if (fStatus != null && ConstData.EMPTY_STRING != fStatus)
            {
                predicate = predicate.And(cat => cat.FStatus.Equals(fStatus));
            }

            List<BdCategory> prodCategories = null;
            var query = dbEntities.BdCategory.Where(predicate);
            totalCount = query.Count();
            if (isDesc)
            {
                prodCategories = query.OrderByDescending(cat => cat.FModifyTime).Skip(start).Take(limit).ToList();
            }
            else
            {
                prodCategories = query.OrderBy(cat => cat.FModifyTime).Skip(start).Take(limit).ToList();
            }
            return new DAOResult<BdCategory>(true, null, prodCategories);

        }

        public DAOResult<BdCategory> findProdUnitTypes(String fId, String fOrgunited, String fName, String fNumber, String fRemark, String fStatus, Boolean isDesc, int start, int limit, out int totalCount)
        {

            return findBdCategories(fId, fOrgunited, ConstData.CATEGORY_PROD_UNIT_TYPE, fName, fNumber, fRemark, fStatus, isDesc, start, limit, out totalCount);

        }

        public DAOResult<BdCategory> findProdStatusTypes(String fId, String fOrgunited, String fName, String fNumber, String fRemark, Boolean isDesc, int start, int limit, out int totalCount)
        {

            return findBdCategories(fId, fOrgunited, ConstData.CATEGORY_PROD_STATUS_TYPE, fName, fNumber, fRemark, null, isDesc, start, limit, out totalCount);

        }

        public DAOResult<BdCategory> findProdPriceTypes(String fId, String fOrgunited, String fName, String fNumber, String fRemark, Boolean isDesc, int start, int limit, out int totalCount)
        {

            return findBdCategories(fId, fOrgunited, ConstData.CATEGORY_PROD_PRICE_TYPE, fName, fNumber, fRemark, null, isDesc, start, limit, out totalCount);

        }


        /// <summary>
        /// 更改或保存BdCategory信息
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public DAOResult<String> saveOrUpdateBdCategory(BdCategory category)
        {
            String FID = null;
            if (category.FId == null || ConstData.EMPTY_STRING == category.FId) //新增
            {
                if (category.FOrgunitId == null || ConstData.EMPTY_STRING == category.FOrgunitId)
                {
                    return new DAOResult<String>(false, "公司的Id信息为空，无法保存", null);
                }
                else
                {
                    IBdOrgunitDao orgDao = new BdOrgunitDaoImpl();
                    List<BdOrgunit> orgunits = orgDao.findOrgunit(category.FOrgunitId, null, null, 0, 1).resultSet;
                    if (orgunits.Count <= 0)
                    {
                        return new DAOResult<String>(false, "该商家ID不存在，保存失败", null);
                    }
                    else
                    {
                        List<BdCategory> ifCates = (from cate in dbEntities.BdCategory where cate.FName == category.FName && cate.FOrgunitId == category.FOrgunitId && cate.FStatus.Equals(ConstData.CATEGORY_STATUS_YES) select cate).ToList<BdCategory>();
                        if (ifCates.Count > 0)
                        {
                            return new DAOResult<String>(false, "该规格存在，保存失败", null);
                        }
                        category.FId = GuidUtils.getGuid();
                        FID = category.FId;
                        category.FStatus = ConstData.CATEGORY_STATUS_YES;
                        dbEntities.BdCategory.AddObject(category);
                    }
                }
            }
            else //更新
            {
                int totalCount = 0;
                DAOResult<BdCategory> result = findBdCategories(category.FId, null, null, null, null, null, ConstData.CATEGORY_STATUS_YES, false, 0, 1, out totalCount);
                IBdOrgunitDao orgDao = new BdOrgunitDaoImpl();
                List<BdOrgunit> orgunits = orgDao.findOrgunit(category.FOrgunitId, null, null, 0, 1).resultSet;
                if (orgunits.Count <= 0)
                {
                    return new DAOResult<String>(false, "该商家ID不存在，保存失败", null);
                }
                List<BdCategory> ifCates = (from cate in dbEntities.BdCategory where cate.FName == category.FName && cate.FOrgunitId == category.FOrgunitId select cate).ToList<BdCategory>();

                if (ifCates.Count > 0)
                {
                    BdCategory cateTest = ifCates.First();
                    if (cateTest.FId != category.FId)
                    {
                        return new DAOResult<String>(false, "该规格存在，保存失败", null);
                    }
                }
                BdCategory bdcategory = null;
                if (result.result && result.resultSet.Count > 0)
                {
                    bdcategory = result.resultSet.First<BdCategory>();
                    bdcategory.FName = category.FName;
                    bdcategory.FNumber = category.FNumber;
                    bdcategory.FModifyTime = category.FModifyTime;
                    bdcategory.FModifierId = category.FModifierId;
                    bdcategory.FOrder = category.FOrder;
                    bdcategory.FRemark = category.FRemark;
                    bdcategory.FOrgunitId = category.FOrgunitId;
                    bdcategory.FStatus = ConstData.CATEGORY_STATUS_YES;
                    FID = bdcategory.FId;

                }
                else
                {
                    return new DAOResult<String>(false, "该记录在数据库中不存在，无法保存", null);
                }
            }
            dbEntities.SaveChanges();
            List<String> resultSet = new List<String>();
            resultSet.Add(FID);
            return new DAOResult<String>(true, null, resultSet);
        }


        public DAOResult<BdCategory> deleteProdCategory(String fId)
        {
            int totalCount = 0;
            DAOResult<BdCategory> result = findBdCategories(fId, null, null, null, null, null, ConstData.CATEGORY_STATUS_YES, false, 0, 1, out totalCount);
            if (result.result)
            {
                BdCategory category = result.resultSet.First<BdCategory>();
                if (category != null)
                {

                    List<String> bdproducts = (from prod in dbEntities.BdProduct where (prod.BdCategory.FId == fId && prod.BdCategory1.FType == ConstData.CATEGORY_PROD_STATUS_TYPE && prod.BdCategory1.FName == ConstData.PRODUCT_STATUS_YES) select prod.FId).ToList<String>();
                    if (bdproducts.Count > 0)
                    {
                        return new DAOResult<BdCategory>(false, "该规格信息被其他产品引用，无法删除", null);
                    }

                    category.FStatus = ConstData.CATEGORY_STATUS_NO;
                }
                else
                {
                    return new DAOResult<BdCategory>(false, "该信息在数据库中不存在，无法删除", null);
                }
            }
            else
            {
                return new DAOResult<BdCategory>(false, "该信息在数据库中不存在，无法删除", null);
            }
            dbEntities.SaveChanges();
            return new DAOResult<BdCategory>(true, null, null);

        }


        /// <summary>
        /// 根据FType获取Category列表
        /// </summary>
        /// <param name="FType"></param>
        /// <author>梁建东</author>
        /// <returns></returns>
        public List<BdCategory> QueryCategoryListByFType(String FType)
        {
            List<BdCategory> list = (from bc in dbEntities.BdCategory where bc.FType == FType orderby bc.FOrder ascending select bc).ToList<BdCategory>();
            return list;
        }

        /// <summary>
        /// 根据FType和FNumber获取Category的FId
        /// </summary>
        /// <param name="FType"></param>
        /// <param name="FNumber"></param>
        /// <author>梁建东</author>
        /// <returns></returns>
        public string QueryCategoryFIdByFTypeAndFNumber(String FType, String FNumber)
        {
            List<string> list = (from bc in dbEntities.BdCategory where bc.FType == FType && bc.FNumber == FNumber select bc.FId).ToList<string>();
            if (list != null && list.Count > 0)
            {
                return list.First<string>();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 根据FId获取资料分类
        /// </summary>
        /// <param name="FId"></param>
        /// <author>姚少鹏</author>
        /// <returns></returns>
        public BdCategory getCategoryByFId(string FId)
        {
            BdCategory obj = null;

            List<BdCategory> categoryList = (from ba in dbEntities.BdCategory where ba.FId == FId select ba).ToList<BdCategory>();
            if (categoryList != null && categoryList.Count > 0)
                obj = categoryList.First();

            return obj;
        }

        /// <summary>
        /// 根据FName和FType获取资料分类
        /// </summary>
        /// <param name="FName">状态名称</param>
        /// <param name="FType">状态类型</param>
        /// <author>姚少鹏</author>
        /// <returns></returns>
        public BdCategory getCategory(string FName, string FType)
        {
            BdCategory obj = null;

            List<BdCategory> categoryList = (from ba in dbEntities.BdCategory where ba.FName == FName && ba.FType == FType select ba).ToList<BdCategory>();
            if (categoryList != null && categoryList.Count > 0)
                obj = categoryList.First();

            return obj;
        }
    }
}
